package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask  {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理超时订单的方法
     */
    @Scheduled(cron = "0 * * * * ?")
    //@Scheduled(cron = "1/5 * * * * *")
    public void processTimoutOrder(){
        log.info("定时处理支付超时的订单：{}",LocalDateTime.now());
        //计算15分钟前的时间
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT, time);

        if(ordersList !=null && ordersList.size()>0){
            for (Orders orders : ordersList) {
                //自动取消支付超时的订单->状态设为取消，设置更新时间为现在
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("订单支付超时，系统自动取消订单...");
                orders.setCancelTime(LocalDateTime.now());

                //更新数据库
                orderMapper.update(orders);
            }
        }
    }

    /**
     * 定时处理处于派送中的订单
     */

    @Scheduled(cron = "0 0 1 * * ?")
    //@Scheduled(cron = "0/5 * * * * *")
    public void processDeliveryOrder(){
        log.info("定时处理处于派送中的订单:{}",LocalDateTime.now());

        //计算一天前的时间,来获取一天前的订单
        LocalDateTime time = LocalDateTime.now().plusHours(-1);

        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS, time);

        if(ordersList !=null && ordersList.size()>0){
            for (Orders orders : ordersList) {
                //自动取消支付超时的订单->状态设为取消，设置更新时间为现在
                orders.setStatus(Orders.COMPLETED);
                //更新数据库
                orderMapper.update(orders);
            }
        }
    }


}
